package ita.class1.group2.supermarket.common.captain.handler;

import ita.class1.group2.supermarket.common.captain.model.Path;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class RequestHandler {

    public List<Object> handle(Path path, HttpServletRequest request) throws FileUploadException, IOException {
        List<Object> objects = new ArrayList<Object>();

        Map<String, String> params = new HashMap<String, String>();
        params.putAll(parsePathVariables(path, request.getRequestURI(), request.getContextPath()));
        for (Object k: request.getParameterMap().keySet()) {
            params.put(k.toString(), ((String[]) request.getParameterMap().get(k))[0]);
        }
        objects.add(params);

        if (request.getContentType() != null && request.getContentType().trim().startsWith("multipart/form-data")) {
            // process form data
            DiskFileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            objects.add(upload.parseRequest(request));
        } else if (request.getContentType() != null && request.getContentLength() > 0) {
            // process text
            byte[] buff = new byte[request.getContentLength()];
            InputStream is = request.getInputStream();
            is.read(buff);
            is.close();
            objects.add(new String(buff));
        }

        return objects;
    }

    private Map<String, String> parsePathVariables(Path path, String requestURI, String contextPath) {
        return Path.getPathVariables(path, requestURI, contextPath);
    }

}
